package ComExWeb.util;

import ComExWeb.dominio.security.Usuario;
import ComExWeb.service.CRUDService;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.mapping.Component;

/**
 *
 * @author Giliard
 */
public class EmailServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    @EJB
    private CRUDService crudService;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //PrintWriter out = Common.printHeader(request, response, "Thesis Proposal", Common.TYPE_STUDENT);
        try {
            doWork(request, response);


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            doWork(request, response);


        } catch (Exception e) {
            e.printStackTrace();
        }


    }

//    @Override
//    public void getResource(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
//        new ContextualHttpServletRequest(request) {
//
//            @Override
//            public void process() throws IOException {
//                doWork(request, response);
//            }
//        }.run();
//    }
    private void doWork(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String codigo = request.getParameter("codigo");
        String nome = request.getParameter("login");

        //UsuarioDAO usuarioDAO = (UsuarioDAO) Component.getInstance("usuarioDAO");
        Usuario usuario = (Usuario) crudService.executeQuerySingleResult("select o from Usuario o where o.login = ?1", nome);
        String idCriptografado = new StringUtil().md5(usuario.getId().toString());
        if (codigo == null || codigo.equals("")) {
            try {
                response.sendRedirect("http://localhost:8080/grupocompramais");
            } catch (IOException ex) {
                Logger.getLogger(EmailServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        if (codigo.equals(idCriptografado)) {
            usuario.setEmailConfirmado(true);
            crudService.save(usuario);
            response.sendRedirect("http://localhost:8080/grupocompramais"
                    + "/confirmacao_cadastro.xhtml");
        } else {
        }
    }
}
